import { NextRequest, NextResponse } from 'next/server';
import { prisma } from '@/app/prisma/client';
import getUserId from '@/utils/getUserId';

export async function DELETE(req: NextRequest, { params }: { params: { groupId: string; memberId: string } }) {
  try {
    const operatorId = getUserId(req);
    if (!operatorId) {
      return NextResponse.json({ error: '请先登录' }, { status: 401 });
    }

    const { groupId, memberId } = params;

    if (operatorId === memberId) {
      return NextResponse.json({ error: '不能将自己移出群组' }, { status: 400 });
    }

    // 1. 验证操作者是否为群主
    const group = await prisma.group.findUnique({
      where: { id: groupId },
    });

    if (!group) {
      return NextResponse.json({ error: '群组不存在' }, { status: 404 });
    }

    if (group.ownerId !== operatorId) {
      return NextResponse.json({ error: '只有群主才能移出成员' }, { status: 403 });
    }

    // 2. 验证被移除者是群成员
    const membershipToRemove = await prisma.groupMember.findFirst({
      where: {
        groupId: groupId,
        userId: memberId,
      },
    });

    if (!membershipToRemove) {
      return NextResponse.json({ error: '该用户不是群组成员' }, { status: 404 });
    }

    // 3. 执行删除
    await prisma.groupMember.delete({
      where: {
        id: membershipToRemove.id,
      },
    });

    return NextResponse.json({ message: '成员已成功移出' });

  } catch (error) {
    console.error('移出群成员失败:', error);
    return NextResponse.json({ error: '服务器错误' }, { status: 500 });
  }
} 